package com.tianyalei.wolf.sample.activity.wxcircle.adater;

import android.app.Activity;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.tianyalei.wolf.mddesignlib.utils.ToastUtil;
import com.tianyalei.wolf.sample.R;
import com.tianyalei.wolf.sample.activity.wxcircle.adater.common.WXCommonAdapter;
import com.tianyalei.wolf.sample.activity.wxcircle.adater.common.WXViewHolder;
import com.tianyalei.wolf.sample.activity.wxcircle.bean.ActionItem;
import com.tianyalei.wolf.sample.activity.wxcircle.bean.CircleItem;
import com.tianyalei.wolf.sample.activity.wxcircle.bean.CommentConfig;
import com.tianyalei.wolf.sample.activity.wxcircle.bean.CommentItem;
import com.tianyalei.wolf.sample.activity.wxcircle.bean.FavortItem;
import com.tianyalei.wolf.sample.activity.wxcircle.data.DatasUtil;
import com.tianyalei.wolf.sample.activity.wxcircle.imagedetail.ViewPagerAdapter;
import com.tianyalei.wolf.sample.activity.wxcircle.imagedetail.ZoomTutorial;
import com.tianyalei.wolf.sample.activity.wxcircle.mvp.presenter.CirclePresenter;
import com.tianyalei.wolf.sample.activity.wxcircle.spannable.ISpanClick;
import com.tianyalei.wolf.sample.activity.wxcircle.widget.CommentListView;
import com.tianyalei.wolf.sample.activity.wxcircle.widget.FavortListView;
import com.tianyalei.wolf.sample.activity.wxcircle.widget.MultiImageView;
import com.tianyalei.wolf.sample.activity.wxcircle.widget.SnsPopupWindow;
import com.tianyalei.wolf.sample.activity.wxcircle.widget.dialog.CommentDialog;
import com.tianyalei.wolf.sample.application.MyApplication;
import com.tianyalei.wolf.sample.imageload.ImageLoadProxy;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yiw
 * @ClassName: CircleAdapter
 * @Description: 圈子列表的adapter
 * @date 2015-12-28 上午09:37:23
 */
public class CircleAdapter extends WXCommonAdapter<CircleItem> {
    private static final String ITEM_TYPE_URL = "1";
    private static final String ITEM_TYPE_IMAGE = "2";
    private static final int ITEM_VIEW_TYPE_COUNT = 3;

    private static final int ITEM_VIEW_TYPE_DEFAULT = 0;
    private static final int ITEM_VIEW_TYPE_URL = 1;
    private static final int ITEM_VIEW_TYPE_IMAGE = 2;

    private CirclePresenter mPresenter;

    public void setCirclePresenter(CirclePresenter presenter) {
        mPresenter = presenter;
    }

    public CircleAdapter(Context context, List<CircleItem> datas) {
        super(context, datas, R.layout.adapter_circle_item);
    }

    public void setDatas(List<CircleItem> datas) {
        mDatas.clear();
        mDatas.addAll(datas);
        notifyDataSetChanged();
    }

    public void addDatas(List<CircleItem> datas) {
        mDatas.addAll(datas);
        notifyDataSetChanged();
    }

    public List<CircleItem> getDatas() {
        return mDatas;
    }

    @Override
    public int getItemViewType(int position) {
        int itemType;
        CircleItem item = mDatas.get(position);
        if (ITEM_TYPE_URL.equals(item.getType())) {
            itemType = ITEM_VIEW_TYPE_URL;
        } else if (ITEM_TYPE_IMAGE.equals(item.getType())) {
            itemType = ITEM_VIEW_TYPE_IMAGE;
        } else {
            itemType = ITEM_VIEW_TYPE_DEFAULT;
        }
        return itemType;
    }

    @Override
    public int getViewTypeCount() {
        return ITEM_VIEW_TYPE_COUNT;
    }

    @Override
    public void convert(WXViewHolder helper, CircleItem circleItem) {
        SimpleDraweeView headIv = helper.getView(R.id.headIv);
        TextView nameTv = helper.getView(R.id.nameTv);
        View digLine = helper.getView(R.id.lin_dig);
        TextView contentTv = helper.getView(R.id.contentTv);
        TextView timeTv = helper.getView(R.id.timeTv);
        TextView deleteBtn = helper.getView(R.id.deleteBtn);

        FavortListView favortListTv = helper.getView(R.id.favortListTv);
        CommentListView commentList = helper.getView(R.id.commentList);

        String name = circleItem.getUser().getName();
        String headImg = circleItem.getUser().getHeadUrl();
        String content = circleItem.getContent();
        String createTime = circleItem.getCreateTime();

        ImageLoadProxy.displayImage(headImg, headIv);
        nameTv.setText(name);
        timeTv.setText(createTime);
        contentTv.setText(content);
        contentTv.setVisibility(TextUtils.isEmpty(content) ? View.GONE : View.VISIBLE);

        //图片的处理，或者是分享的链接的处理
        doUrlTip(circleItem, helper);

        doPopupWindow(helper.getView(R.id.snsBtn), circleItem);

        doDeleteBtn(deleteBtn, circleItem);

        boolean hasComment = circleItem.hasComment();
        boolean hasFavort = circleItem.hasFavort();
        LinearLayout digCommentBody = helper.getView(R.id.digCommentBody);
        if (!hasFavort && !hasComment) {
            digCommentBody.setVisibility(View.GONE);
        }

        //分隔线处理
        digLine.setVisibility(hasFavort && hasComment ? View.VISIBLE : View.GONE);
        //点赞处理
        doFavorList(favortListTv, circleItem);
        //评论处理
        doCommentList(commentList, circleItem);
    }

    @Override
    public void initLayout(WXViewHolder helper, int position) {
        int itemViewType = getItemViewType(position);
        ViewStub linkOrImgViewStub = helper.getView(R.id.linkOrImgViewStub);
        switch (itemViewType) {
            case ITEM_VIEW_TYPE_URL:// 链接view
                linkOrImgViewStub.setLayoutResource(R.layout.viewstub_urlbody);
                linkOrImgViewStub.inflate();
                break;
            case ITEM_VIEW_TYPE_IMAGE:// 图片view
                linkOrImgViewStub.setLayoutResource(R.layout.viewstub_imgbody);
                linkOrImgViewStub.inflate();
                break;
        }
    }

    private void doUrlTip(CircleItem circleItem, WXViewHolder helper) {
        TextView urlTipTv = helper.getView(R.id.urlTipTv);
        urlTipTv.setVisibility(View.GONE);

        int position = mDatas.indexOf(circleItem);
        int itemViewType = getItemViewType(position);


        switch (itemViewType) {
            case ITEM_VIEW_TYPE_URL:// 处理链接动态的链接内容和和图片
                LinearLayout urlBodyView = helper.getView(R.id.urlBody);

                if (urlBodyView != null) {
                    String linkImg = circleItem.getLinkImg();
                    String linkTitle = circleItem.getLinkTitle();
                    TextView urlContentTv = helper.getView(R.id.urlContentTv);
                    SimpleDraweeView urlImageIv = helper.getView(R.id.urlImageIv);
                    ImageLoadProxy.displayImage(linkImg, urlImageIv);
                    urlContentTv.setText(linkTitle);
                    urlBodyView.setVisibility(View.VISIBLE);
                    urlTipTv.setVisibility(View.VISIBLE);
                }

                break;
            case ITEM_VIEW_TYPE_IMAGE:// 处理图片
                MultiImageView multiImageView = helper.getView(R.id.multiImagView);

                if (multiImageView != null) {
                    final List<String> photos = circleItem.getPhotos();

                    if (photos == null || photos.size() == 0) {
                        multiImageView.setVisibility(View.GONE);
                        return;
                    }
                    multiImageView.setVisibility(View.VISIBLE);
                    multiImageView.setList(photos);
                    multiImageView.setOnItemClickListener(new MultiImageView.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            // 因为单张图片时，图片实际大小是自适应的，imageLoader缓存时是按测量尺寸缓存的
//                        ImagePagerActivity.imageSize = new ImageSize(view.getMeasuredWidth(), view.getMeasuredHeight());
//                        ImagePagerActivity.startImagePagerActivity(mContext, photos, position);
                            setViewPagerAndZoom(photos, view, position);
                        }
                    });
                }

                break;
            default:
                break;
        }
    }

    private ZoomTutorial mZoomTutorial;
    private List<View> guideViewList = new ArrayList<>(8);

    public void setViewPagerAndZoom(List<String> photos, View v, int position) {
        //得到要放大展示的视图界面
        View view = ((Activity) mContext).findViewById(R.id.detail_view);
        ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
        LinearLayout guideGroup = (LinearLayout) view.findViewById(R.id.guideGroup);
        guideGroup.removeAllViews();
        //最外层的容器，用来计算
        View containerView = ((Activity) mContext).findViewById(R.id.container);
        //实现放大缩小类，传入当前的容器和要放大展示的对象
        mZoomTutorial = new ZoomTutorial(photos.size(), containerView, view);

        ViewPagerAdapter adapter = new ViewPagerAdapter(mContext, photos, mZoomTutorial);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(position);


        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < guideViewList.size(); i++) {
                    guideViewList.get(i).setSelected(i == position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        addGuideView(guideGroup, position, photos);

        // 通过传入Id来从小图片扩展到大图，开始执行动画
        mZoomTutorial.zoomImageFromThumb(v);
        mZoomTutorial.setOnZoomListener(new ZoomTutorial.OnZoomListener() {

            @Override
            public void onThumbed() {
                // TODO 自动生成的方法存根
                System.out.println("现在是-------------------> 小图状态");
            }

            @Override
            public void onExpanded() {
                // TODO 自动生成的方法存根
                System.out.println("现在是-------------------> 大图状态");
            }
        });
    }

    private void addGuideView(LinearLayout guideGroup, int startPos, List<String> imgUrls) {
        if (imgUrls != null && imgUrls.size() > 0) {
            guideViewList.clear();
            for (int i = 0; i < imgUrls.size(); i++) {
                View view = new View(mContext);
                view.setBackgroundResource(R.drawable.selector_guide_bg);
                view.setSelected(i == startPos);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(mContext.getResources().getDimensionPixelSize(R.dimen.gudieview_width),
                        mContext.getResources().getDimensionPixelSize(R.dimen.gudieview_heigh));
                layoutParams.setMargins(10, 0, 0, 0);
                guideGroup.addView(view, layoutParams);
                guideViewList.add(view);
            }
        }
    }

    /**
     * 点击返回键时，如果正在展示大图，就关闭大图
     */
    public void closeViewDetail() {
        View view = ((Activity) mContext).findViewById(R.id.detail_view);
        ViewPager expandedView = (ViewPager) view.findViewById(R.id.viewpager);
        //得到要放大展示的视图界面
//        ViewPager expandedView = (ViewPager) ((Activity) mContext).findViewById(R.id.detail_view);
        int position = expandedView.getCurrentItem();
        mZoomTutorial.closeZoomAnim(position);
    }

    /**
     * 删除按钮的处理
     *
     * @param deleteBtn
     * @param circleItem
     */
    private void doDeleteBtn(TextView deleteBtn, final CircleItem circleItem) {
        if (DatasUtil.curUser.getId().equals(circleItem.getUser().getId())) {
            deleteBtn.setVisibility(View.VISIBLE);
        } else {
            deleteBtn.setVisibility(View.GONE);
        }
        deleteBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除
                if (mPresenter != null) {
                    mPresenter.deleteCircle(circleItem.getId());
                }
            }
        });
    }

    /**
     * 评论列表处理
     *
     * @param commentList
     * @param circleItem
     */
    private void doCommentList(CommentListView commentList, final CircleItem circleItem) {
        boolean hasComment = circleItem.hasComment();
        if (!hasComment) {
            commentList.setVisibility(View.GONE);
            return;
        }

        final int position = mDatas.indexOf(circleItem);
        //处理评论列表
        final List<CommentItem> commentsDatas = circleItem.getComments();
        commentList.setOnItemClick(new CommentListView.OnItemClickListener() {
            @Override
            public void onItemClick(int commentPosition) {
                CommentItem commentItem = commentsDatas.get(commentPosition);
                if (DatasUtil.curUser.getId().equals(commentItem.getUser().getId())) {//复制或者删除自己的评论

                    CommentDialog dialog = new CommentDialog(mContext, mPresenter, commentItem, position);
                    dialog.show();
                } else {//回复别人的评论
                    if (mPresenter != null) {
                        CommentConfig config = new CommentConfig();
                        config.circlePosition = position;
                        config.commentPosition = commentPosition;
                        config.commentType = CommentConfig.Type.REPLY;
                        config.replyUser = commentItem.getUser();
                        mPresenter.showEditTextBody(config);
                    }
                }
            }
        });
        commentList.setOnItemLongClick(new CommentListView.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(int commentPosition) {
                //长按进行复制或者删除
                CommentItem commentItem = commentsDatas.get(commentPosition);
                CommentDialog dialog = new CommentDialog(mContext, mPresenter, commentItem, position);
                dialog.show();
            }
        });
        CommentAdapter commentAdapter = new CommentAdapter(mContext);
        commentAdapter.setDatas(commentsDatas);
        commentList.setAdapter(commentAdapter);
        commentAdapter.notifyDataSetChanged();

        commentList.setVisibility(View.VISIBLE);
    }

    /**
     * 处理点赞列表
     *
     * @param favortListTv
     * @param circleItem
     */
    private void doFavorList(FavortListView favortListTv, CircleItem circleItem) {
        boolean hasFavort = circleItem.hasFavort();
        if (!hasFavort) {
            favortListTv.setVisibility(View.GONE);
            return;
        }

        //处理点赞列表
        final List<FavortItem> favortDatas = circleItem.getFavorters();
        FavortListAdapter favortListAdapter = new FavortListAdapter();
        favortListTv.setSpanClickListener(new ISpanClick() {
            @Override
            public void onClick(int position) {
                String userName = favortDatas.get(position).getUser().getName();
                String userId = favortDatas.get(position).getUser().getId();
                ToastUtil.showToast(MyApplication.getInstance(), userName + " &id = " + userId);
            }
        });
        favortListAdapter.setDatas(favortDatas);
        favortListTv.setAdapter(favortListAdapter);
        favortListAdapter.notifyDataSetChanged();

        favortListTv.setVisibility(View.VISIBLE);
    }

    /**
     * 点赞按钮的点击响应
     *
     * @param snsBtn
     * @param circleItem
     */
    private void doPopupWindow(View snsBtn, final CircleItem circleItem) {
        snsBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                SnsPopupWindow snsPopupWindow = new SnsPopupWindow(mContext);
                //判断是否已点赞
                String curUserFavortId = circleItem.getCurUserFavortId(DatasUtil.curUser.getId());
                if (!TextUtils.isEmpty(curUserFavortId)) {
                    snsPopupWindow.getmActionItems().get(0).mTitle = "取消";
                } else {
                    snsPopupWindow.getmActionItems().get(0).mTitle = "赞";
                }
                snsPopupWindow.update();
                //弹出popupwindow
                snsPopupWindow.showPopupWindow(view);
                snsPopupWindow.setmItemClickListener(new PopupItemClickListener(mDatas.indexOf(circleItem), circleItem, curUserFavortId));
            }
        });
    }

    private class PopupItemClickListener implements SnsPopupWindow.OnItemClickListener {
        private String mFavorId;
        //动态在列表中的位置
        private int mCirclePosition;
        private long mLasttime = 0;

        public PopupItemClickListener(int circlePosition, CircleItem circleItem, String favorId) {
            this.mFavorId = favorId;
            this.mCirclePosition = circlePosition;
        }

        @Override
        public void onItemClick(ActionItem actionitem, int position) {
            switch (position) {
                case 0://点赞、取消点赞
                    if (System.currentTimeMillis() - mLasttime < 700)//防止快速点击操作
                        return;
                    mLasttime = System.currentTimeMillis();
                    if (mPresenter != null) {
                        if ("赞".equals(actionitem.mTitle.toString())) {
                            mPresenter.addFavort(mCirclePosition);
                        } else {//取消点赞
                            mPresenter.deleteFavort(mCirclePosition, mFavorId);
                        }
                    }
                    break;
                case 1://发布评论
                    if (mPresenter != null) {
                        CommentConfig config = new CommentConfig();
                        config.circlePosition = mCirclePosition;
                        config.commentType = CommentConfig.Type.PUBLIC;
                        mPresenter.showEditTextBody(config);
                    }
                    break;
                default:
                    break;
            }
        }
    }

}
